<!-- src/views/auth/Register.vue -->
<template>
  <div class="register-container">
    <el-card class="register-card">
      <h1>欢迎注册 {{ projectStore.getProjectName }}</h1>
      <h2>注册</h2>
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        @submit.prevent="onSubmit"
      >
        <el-form-item
          v-for="field in userFields"
          :key="field.key"
          :prop="field.key"
        >
          <el-input
            v-if="field.type === 'text' || field.type === 'password'"
            v-model="form[field.key]"
            :type="field.type"
            :placeholder="field.placeholder"
            :prefix-icon="getIcon(field.key)"
            :show-password="field.type === 'password'"
            clearable
          />
          <el-select
            v-else-if="field.type === 'select'"
            v-model="form[field.key]"
            :placeholder="field.placeholder"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="option in roleOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
              :disabled="option.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            native-type="submit"
            style="width: 100%"
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-link type="primary" @click="$router.push('/login')"
            >已有账号？去登录</el-link
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessage, type FormInstance } from 'element-plus';
import { useRouter } from 'vue-router';
import { useUserStore, userFields, type UserField } from '@/stores/user';
import { useRoleStore } from '@/stores/project/role';
import { useProjectStore } from '@/stores/project/project';
import { User, Lock, UserFilled } from '@element-plus/icons-vue';

const router = useRouter();
const userStore = useUserStore();
const roleStore = useRoleStore();
const projectStore = useProjectStore();

// 使用 roleNames 作为 el-select 的选项
const roleOptions = computed(() => roleStore.roleNames);

// 动态表单数据
const form = ref<Record<string, string>>({});
userFields.forEach((field) => {
  form.value[field.key] = field.type === 'select' ? 'EMPLOYEE' : '';
});

// 动态验证规则
const rules = computed(() => {
  const result: Record<string, any[]> = {};
  userFields.forEach((field) => {
    const fieldRules = [];
    if (field.required) {
      fieldRules.push({
        required: true,
        message: field.placeholder || `请输入${field.label}`,
        trigger: field.type === 'select' ? 'change' : 'blur',
      });
    }
    if (field.minLength) {
      fieldRules.push({
        min: field.minLength,
        message: `${field.label}长度至少${field.minLength}位`,
        trigger: 'blur',
      });
    }
    result[field.key] = fieldRules;
  });
  return result;
});

// 表单引用
const formRef = ref<FormInstance | null>(null);

// 加载状态
const loading = ref(false);

// 动态图标
const getIcon = (key: string) => {
  const iconMap: Record<string, any> = {
    username: User,
    password: Lock,
    realName: UserFilled,
  };
  return iconMap[key] || User;
};

// 表单提交
const onSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;
    await userStore.register(form.value);
    ElMessage.success('注册成功');
    router.push('/');
  } catch (error) {
    console.log(error);
    ElMessage.error('注册失败，请检查输入信息');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.register-card {
  width: 400px;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 10px;
  font-size: 24px;
  color: #409eff;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}
</style>